﻿#region

using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;

#endregion

namespace Radovici.Ctrls.Facebook
{
    [TemplateVisualState(Name = "NotPublished", GroupName = "PostStates")]
    [TemplateVisualState(Name = "Published", GroupName = "PostStates")]
    public class FacebookPost : ContentControl
    {
        #region Private fields

        private FacebookApi _api;

        #endregion

        public static readonly DependencyProperty ApiKeyProperty = DependencyProperty.Register("ApiKey", typeof (string),
                                                                                               typeof (FacebookConnect),
                                                                                               new PropertyMetadata(
                                                                                                   null, OnApiKeyChanged));

        public FacebookPost()
        {
            DefaultStyleKey = typeof (FacebookPost);
        }

        public string ApiKey
        {
            get { return (string) GetValue(ApiKeyProperty); }
            set { SetValue(ApiKeyProperty, value); }
        }

        // Using a DependencyProperty as the backing store for ApiKey.  This enables animation, styling, binding, etc...

        private static void OnApiKeyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var connect = d as FacebookPost;
            if (connect != null)
            {
                if (connect._api != null)
                {
                    connect._api.PropertyChanged -= connect.OnFacebookApiChanged;
                }
                var apiKey = e.NewValue as string;
                if (apiKey != null)
                {
                    connect._api = FacebookApi.GetFacebookApi(apiKey); // new FacebookApi(apiKey);
                    connect._api.PropertyChanged += connect.OnFacebookApiChanged;
                    connect.OnApplyTemplate();
                }
            }
        }

        private void OnFacebookApiChanged(object sender, PropertyChangedEventArgs e)
        {
            UpdateStates();
        }

        private void UpdateStates()
        {
            UpdateStates(true);
        }

        private void UpdateStates(bool useTransitions)
        {
            if (true)
            {
                VisualStateManager.GoToState(this, "NotPublished", useTransitions);
            }
            else
            {
                VisualStateManager.GoToState(this, "Published", useTransitions);
            }
        }
    }
}